package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.BulletList;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.HeadingTag;
import org.htmlparser.tags.Span;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDrawPrizeItem;
import com.lehecai.core.util.CoreDateUtils;
import com.lehecai.core.util.CoreFetcherUtils;

/**
 * 西南彩票网 开奖结果抓取
 * 主要抓取云贵川天天乐  <br/>
 * 历史地址:  http://www.xinancaipiao.com/info_ttl.aspx?tc=2013132<br/>
 * @author 
 *
 */
public class LotteryDrawFetch519WorkerOfficial extends AbstractLotteryDrawFetchWorker{

	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	protected static final String RESULT_LOCALITY_URL = "http://www.xinancaipiao.com/kjgg.aspx";
	protected static final String RESULT_HISTORY_LOCALITY_URL = "http://www.xinancaipiao.com/info_ttl.aspx?tc=%s";
	
	protected String siteName = "西南彩票网";
	protected String lotteryScope = "云贵川天天乐";
	
	public LotteryDrawFetch519WorkerOfficial(){
		super(LotteryType.A_YGCTTL);
	}
	@Override
	public LotteryDraw fetchResult(String phase) {
		return null;
	}
	
	private String fetchLatestLotteryPhase(){
		String url = RESULT_LOCALITY_URL;
		String data = null;
		String pageInfo = "彩期为null时获取结果页面" + url;
		String encoding = "GBK";
		String logHeader = "==" + lotteryScope + "==" + siteName + "==" + pageInfo + "==抓取==" + getLotteryType().getName() + "==";
		
		String phase = "";		
		try {
			data = CoreFetcherUtils.URLGet(url, null, encoding);
		} catch (Exception e) {
			logger.error("获取html数据失败" + e.getMessage());
			return null;
		}
		
		if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
			logger.error(logHeader + "data is null or 404 Not Found");
			return null;
		}	
		Parser parser = null;
		
		try {
			parser = Parser.createParser(data,  encoding);
		} catch (Exception e) {
			logger.error("解析html页面失败" + e.getMessage());
			return null;
		}
		
		NodeFilter filter = new HasAttributeFilter("class", "kaij");		
		NodeList nodeList = null;
		
		try {
			nodeList = parser.extractAllNodesThatMatch(filter);
			Div divTag = (Div) nodeList.elementAt(0);
			NodeList divChildren = divTag.getChildren();
			for (int i = 0; i < divChildren.size(); i++) {
				Node node = divChildren.elementAt(i);
				if (node instanceof BulletList) {
					BulletList ulList = (BulletList)node;
					String lotteryNameHtml = ulList.getChild(1).toPlainTextString();
					if (lotteryNameHtml.indexOf("天天乐") > 0) {
						String lotteryPhaseHtml = ulList.getChild(3).toPlainTextString().trim();
						lotteryPhaseHtml = StringUtils.replace(lotteryPhaseHtml, "期", "");
						phase = lotteryPhaseHtml;
						break;
					}
				}
			}
		} catch (ParserException e) {
			logger.error("数据解析错误==" + e.getMessage(), e);
			return null;
		}
		return phase;
	}

	@Override
	public LotteryDraw fetchResultDetail(String phase) {
		
		if (phase == null || "".equals(phase)) {
			phase = fetchLatestLotteryPhase();
			if (StringUtils.isEmpty(phase)) {
				return null;
			}
		} else if(phase.length() == 5){
			phase = "20" + phase;
		}
		
		String url = String.format(RESULT_HISTORY_LOCALITY_URL, phase);
		String data = null;
		String pageInfo = "结果页面" + url;
		String encoding = "GBK";
		String logHeader = "==" + lotteryScope + "==" + siteName + "=="
				+ pageInfo + "==抓取==" + getLotteryType().getName() + "==";
		
		LotteryDraw lotteryDraw = new LotteryDraw();
		try {
			data = CoreFetcherUtils.URLGet(url, null, encoding);
		} catch (Exception e) {
			logger.error("获取html数据失败" + e.getMessage());
			return null;
		}
		
		if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
			logger.error(logHeader + "data is null or 404 Not Found");
			return null;
		}	
		Parser parser = null;
		try {
			parser = Parser.createParser(data,  encoding);
		} catch (Exception e) {
			logger.error("解析html页面失败" + e.getMessage());
			return null;
		}
		
		NodeFilter tableFilter = new TagNameFilter("table");
		NodeFilter h4Filter = new TagNameFilter("h4");
		NodeFilter spanFilter = new TagNameFilter("span");
		NodeList tableNodeList = null;
		NodeList h4NodeList = null;
		NodeList spanNodeList = null;
		String strDate = "", strResult = "";
		
		try {
			tableNodeList = parser.extractAllNodesThatMatch(tableFilter);
			
			//获取中奖号码
			TableTag drawNumberTableTag = (TableTag) tableNodeList.elementAt(0);
			TableRow[] tableRows = drawNumberTableTag.getRows();
			TableColumn[] tableColumns = tableRows[1].getColumns();//第二行
			int num = 0;
			for (TableColumn numColumn : tableColumns) {
				String tempNum = numColumn.toPlainTextString().trim(); 
				if (num > 0) {
					strResult += ",";
				}
				strResult += tempNum;
				num++;
			}
			
			lotteryDraw.setLotteryType(this.getLotteryType());
			lotteryDraw.setResult(strResult);
			lotteryDraw.setJackpot(null);
			if (phase.length() == 7) {
				phase = StringUtils.substring(phase, 2);
			}
			lotteryDraw.setPhase(phase);
			
			//获取中奖明细
			TableTag drawDetailTableTag = (TableTag) tableNodeList.elementAt(1);
			TableRow[] tableDetailRows = drawDetailTableTag.getRows();
			List<LotteryDrawPrizeItem> itemList = new ArrayList<LotteryDrawPrizeItem>();
			for (int i = 1;i<tableDetailRows.length; i++) {//第2至第4行
				TableColumn[] tableDetailColumns = tableDetailRows[i].getColumns();
				LotteryDrawPrizeItem item = new LotteryDrawPrizeItem();
				for (int j=0; j<tableDetailColumns.length; j++) {
					TableColumn detailColum = tableDetailColumns[j];
					String textStr = detailColum.toPlainTextString().trim();
					if (j == 0) {
						item.setName(textStr);
					} else if (j == 1){
						item.setWinningCount(textStr);
					} else if (j == 2){
						item.setPrizeAmount(textStr);
					}
				}
				itemList.add(item);
			}
			lotteryDraw.setResultDetail(itemList);
			
			//重新设置该parser
			parser.setInputHTML(data);
			//开奖时间
			h4NodeList = parser.extractAllNodesThatMatch(h4Filter);
			HeadingTag h4Node = (HeadingTag)h4NodeList.elementAt(1);
			strDate = h4Node.childAt(0).toPlainTextString().trim();
			lotteryDraw.setTimeDraw(CoreDateUtils.formatDate(CoreDateUtils.parseDate(strDate, "yyyy年MM月dd日"), CoreDateUtils.DATE));
			
			//重新设置该parser
			parser.setInputHTML(data);
			//销售金额
			spanNodeList = parser.extractAllNodesThatMatch(spanFilter);
			Span spanNode = (Span)spanNodeList.elementAt(5);
			String volumeOfSales = StringUtils.replace(spanNode.toPlainTextString().trim(), "元", "");
			lotteryDraw.setVolumeOfSales(volumeOfSales);
			lotteryDraw.setJackpot("0");
			
		} catch (ParserException e) {
			logger.error("数据解析错误==" + e.getMessage(), e);
			return null;
		}
		return lotteryDraw;
	}

	@Override
	protected String getResultDetailUrl(String phase) {
		return null;
	}

	@Override
	protected String getResultUrl(String phase) {
		return null;
	}

}
